package com.hnevc.mytrafficdemo.activity;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.Toast;

import com.hnevc.mytrafficdemo.R;
import com.hnevc.mytrafficdemo.adapter.MyExpandableListViewAdapter;
import com.hnevc.mytrafficdemo.entity.BusStatus;
import com.hnevc.mytrafficdemo.util.httppost.HttpThread;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class QueryBusActivity extends AppCompatActivity {
    Button mBtnDetail;
    ProgressDialog pd;
    private static final String TAG = "QueryBusActivity";

    ExpandableListView mExpandableListView;
    private Map<Integer, List<BusStatus>> mapBusStatusList;
    private Map<Integer, String> mapName;

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == 901){
                Toast.makeText(QueryBusActivity.this, "连接超时", Toast.LENGTH_SHORT).show();
                return;//超时返回，不处理数据
            }
            HttpThread thread = (HttpThread) msg.obj;
            Log.e(TAG, "handleMessage: "+thread.getJsonstring()+"\n"+thread.getResultString());
            //解析数据
            JSONArray array = null;
            JSONObject request=null;
            try {
                array = new JSONArray(thread.getResultString());
                request =new  JSONObject(thread.getJsonstring());
                List<BusStatus> list = new ArrayList<>();
                for (int i = 0; i < array.length(); i++) {
                    JSONObject object = array.getJSONObject(i);
                    BusStatus busStatus = new BusStatus();
                    busStatus.setBusStationId(request.getInt("BusStationId"));
                    busStatus.setBusId(object.getInt("BusId"));
                    busStatus.setCapacity(101);
                    busStatus.setDistance(object.getInt("Distance"));
                    list.add(busStatus);
                }
                mapBusStatusList.put(request.getInt("BusStationId"), list);
                initView();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    private MyExpandableListViewAdapter mAdapter;
    private Timer mTimer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_query_bus);
        pd = new ProgressDialog(this);
        initData();
        initView();
    }

    private void initData() {
        //根据题目，初始化站台数据
        mapName = new HashMap<>();
        mapName.put(1, "中医院站");
        mapName.put(2, "联想大厦站");

        mapBusStatusList = new HashMap<>();
        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
//每个三秒，发送一个站台查询信息
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        pd.show();
                    }
                });
                for (int i = 0; i < mapName.size(); i++) {
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    HttpThread thread = new HttpThread(QueryBusActivity.this, mHandler);
                    //准备访问的网址
                    thread.setUrl("http://192.168.1.142:8080/transportservice/type/jason/action/GetBusStationInfo.do");
                    //准备提交的数据
                    JSONObject object = new JSONObject();
                    try {
                        int currentBusStation = (int) mapName.keySet().toArray()[i];
                        object.put("BusStationId", currentBusStation);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    String jsonString = object.toString();

                    thread.setJsonstring(jsonString);
                    thread.run();
                }
            }
        }, 0 , 60000);


    }

    private void initView() {
        mBtnDetail = (Button) findViewById(R.id.id_btn_detail);
        mBtnDetail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                BusCapacityDialog capacityDialog = new BusCapacityDialog(QueryBusActivity.this);
                capacityDialog.show();
            }
        });
        Log.e(TAG, "initView: " );
        if (mapBusStatusList.size() == mapName.size()) {
            //排序，按照距离升序排列
            for(int i=0;i<mapBusStatusList.size();i++){
                List<BusStatus> busStatuses = mapBusStatusList.get(mapName.keySet().toArray()[i]);
                Collections.sort(busStatuses, new Comparator<BusStatus>() {
                    @Override
                    public int compare(BusStatus bus1, BusStatus bus2) {
                        return bus1.getDistance() - bus2.getDistance();
                    }
                });

            }

            if(mAdapter!=null){
                mAdapter.notifyDataSetChanged();
            }
            else {
                mAdapter = new MyExpandableListViewAdapter(this, mapBusStatusList, mapName);
                mExpandableListView = (ExpandableListView) findViewById(R.id.id_elv);

                mExpandableListView.setAdapter(mAdapter);
                int count = mExpandableListView.getCount();
                for (int i = 0; i < count; i++) {
                    mExpandableListView.expandGroup(i);
                }
            }
            if(pd.isShowing()) {
                pd.dismiss();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(pd.isShowing()){
            pd.dismiss();
        }
        mTimer.cancel();
        mTimer=null;
    }
}
